package com.crazyktv.wcf.android;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.crazyktv.wcf.android.Util.DoAction;
import com.crazyktv.wcf.android.Util.LangList;

@SuppressLint("NewApi")
public class SongQuery extends Activity {
	protected static Vibrator myVibrator = null;
	private int position;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		myVibrator = (Vibrator) getApplication().getSystemService(
				Service.VIBRATOR_SERVICE);

		setMainMenu();
	}

	private LinearLayout layoutMain, layoutMenu, layoutContent;
	private TextView MenuFirst, MenuSecond, MenuThird, MenuFourth;
	private Button btnSinger, btnLanguage, btnFavorite, btnRank, btnLangGuo,
			btnLangTai, btnLangYuei, btnLangJpn, btnLangEng, btnLangKer,
			btnLangOther, btnLangKid, btnWord1, btnWord2, btnWord3, btnWord4,
			btnWord5, btnWord6, btnWord7, btnWord8, btnWord9, btnWord0,
			btnSongName, btnSingerMale, btnSingerFemale, btnSingerGroup,
			btnSingerQuery, btnMulti, btnNewSong;
	private MenuType backAction;
	private ScrollView sv;
	private ListView lv;

	private void setMainMenu() {
		position = 0;
		layoutMain = linearLayout(1, this);
		layoutMenu = linearLayout(0, this);
		layoutMenu.setPadding(10, 5, 0, 10);
		layoutMain.addView(layoutMenu);
		MenuFirst = menuText(MenuType.MAIN, false);
		layoutMenu.addView(MenuFirst);
		btnSinger = contentButton(R.string.songquery_singer);
		btnLanguage = contentButton(R.string.songquery_lang);
		btnMulti = contentButton(R.string.songquery_multi);
		btnFavorite = contentButton(R.string.songquery_favorite);
		btnRank = contentButton(R.string.songquery_rank);
		btnNewSong = contentButton(R.string.songquery_new_song);
		btnSongName = contentButton(R.string.songquery_song_name);
		layoutContent = linearLayout(1, this);
		sv = scrollView(this);
		sv.addView(layoutContent);
		layoutContent.addView(btnSinger);
		layoutContent.addView(btnLanguage);
		layoutContent.addView(btnMulti);
		layoutContent.addView(btnFavorite);
		layoutContent.addView(btnRank);
		layoutContent.addView(btnNewSong);
		layoutContent.addView(btnSongName);
		layoutMain.addView(sv);
		backAction = MenuType.QUIT;
		setContentView(layoutMain);

		btnSinger.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setSingerMenu();
			}
		});
		btnLanguage.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setLangMenu();
			}
		});

		btnMulti.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				setMultiMenu();
			}
		});

		btnFavorite.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				/*
				 * tm = (TelephonyManager)
				 * getSystemService(Context.TELEPHONY_SERVICE); //String imei =
				 * tm.getDeviceId(); getSongList(MenuType.FAVORITE, null, null,
				 * Command.FAVORITELIST.getValue() + ":" + imei + ":");
				 */
				getFavaoriteList();
			}
		});
		btnNewSong.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Calendar c = Calendar.getInstance();
				c.add(Calendar.DAY_OF_MONTH, (int) (Util.prefNewSongInnerDays * -1));
				SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
				String str = df.format(c.getTime());
				str = "Song_CreatDate%20%3E=%20%27"+str+"%27";
				str = str.replace("/", "%2F");
				str = str + "&sort=Song_WordCount,Song_SongName";
				getSongList(MenuType.NEW_SONG, null, null, Util.QuerySong(str));
			}
		});

		btnRank.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setRankMenu();
			}
		});
		btnSongName.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				querySongNameDialog().show();
			}
		});
	}

	private void setSingerMenu() {
		position = 0;
		layoutMain = linearLayout(1, this);
		layoutMenu = linearLayout(0, this);
		layoutMenu.setPadding(10, 5, 0, 10);
		layoutMain.addView(layoutMenu);
		MenuFirst = menuText(MenuType.MAIN, true);
		MenuSecond = menuText(MenuType.SINGER, false);
		layoutMenu.addView(MenuFirst);
		layoutMenu.addView(MenuSecond);
		layoutContent = linearLayout(1, this);
		sv = scrollView(this);
		sv.addView(layoutContent);
		btnSingerMale = contentButton(R.string.songquery_singer_male);
		btnSingerFemale = contentButton(R.string.songquery_singer_female);
		btnSingerGroup = contentButton(R.string.songquery_singer_group);
		btnSingerQuery = contentButton(R.string.songquery_singer_query);
		layoutContent.addView(btnSingerMale);
		layoutContent.addView(btnSingerFemale);
		layoutContent.addView(btnSingerGroup);
		layoutContent.addView(btnSingerQuery);

		layoutMain.addView(sv);
		backAction = MenuType.MAIN;
		setContentView(layoutMain);

		btnSingerMale.setOnClickListener(setSingerOCL(MenuType.SINGER_MALE));
		btnSingerFemale
				.setOnClickListener(setSingerOCL(MenuType.SINGER_FEMALE));
		btnSingerGroup.setOnClickListener(setSingerOCL(MenuType.SINGER_GROUP));
		btnSingerQuery.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				querySingerNameDialog().show();
			}
		});
	}

	private OnClickListener setSingerOCL(final MenuType mt) {
		OnClickListener ocl = new View.OnClickListener() {
			public void onClick(View v) {
				getSingerList(mt);
			}
		};
		return ocl;
	}

	private AlertDialog querySingerNameDialog() {
		// 產生一個Builder物件
		Builder builder = new AlertDialog.Builder(SongQuery.this);
		// 設定Dialog的標題
		builder.setTitle(R.string.songquery_singer_query);
		// 設定Dialog的內容
		final EditText et = new EditText(this);
		builder.setView(et);

		builder.setNegativeButton(android.R.string.cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
				});

		builder.setPositiveButton(android.R.string.ok,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (!(et.getText().length() == 0)) {
							String t = et.getText().toString();
							t = t.replace(" ", "%20");
							t = t.replace("'", "%27");
							getSongList(MenuType.SINGER, MenuType.SINGER_QUERY,
									null, Util.QuerySingerSong(t.toString()));
						}

					}
				});

		// 利用Builder物件建立AlertDialog
		return builder.create();
	}

	private void getSingerList(final MenuType mt) {
		layoutMain = linearLayout(1, this);
		layoutMenu = linearLayout(0, this);
		layoutMenu.setPadding(10, 5, 0, 10);
		layoutMain.addView(layoutMenu);
		MenuFirst = menuText(MenuType.MAIN, true);
		MenuSecond = menuText(MenuType.SINGER, true);
		MenuThird = menuText(mt, false);
		layoutMenu.addView(MenuFirst);
		layoutMenu.addView(MenuSecond);
		layoutMenu.addView(MenuThird);
		lv = listView();

		String list = null;
		switch (mt) {
		case SINGER_MALE:
			list = Util.QuerySinger(0);
			break;
		case SINGER_FEMALE:
			list = Util.QuerySinger(1);
			break;
		case SINGER_GROUP:
			list = Util.QuerySinger(2);
			break;
		default:
		}
		// readJSON
		ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
		try {
			JSONArray jsonArray = new JSONArray(list);
			for (int i = 0; i < jsonArray.length(); i++) {
				HashMap<String, String> map = new HashMap<String, String>();
				JSONObject e = jsonArray.getJSONObject(i);
				map.put("singer", e.getString("Singer_Name"));
				map.put("stroke", e.getString("Singer_Strokes") + " 劃");
				mylist.add(map);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.list1,
				new String[] { "stroke", "singer" }, new int[] { R.id.text1,
						R.id.text2 });
		lv.setAdapter(adapter);
		if (position != 0) {
			lv.setSelection(position);
		}
		registerForContextMenu(lv);
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> a, View v, int position,
					long id) {
				TextView tvSinger = (TextView) v.findViewById(R.id.text2);
				getSongList(MenuType.SINGER, mt, tvSinger.getText().toString(),
						Util.QuerySingerSong(tvSinger.getText().toString()));
			}
		});
		lv.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				position = firstVisibleItem;
			}
		});
		layoutMain.addView(lv);
		backAction = MenuType.SINGER;
		setContentView(layoutMain);
	}

	private void setLangMenu() {
		layoutMain = linearLayout(1, this);
		layoutMenu = linearLayout(0, this);
		layoutMenu.setPadding(10, 5, 0, 10);
		layoutMain.addView(layoutMenu);
		MenuFirst = menuText(MenuType.MAIN, true);
		MenuSecond = menuText(MenuType.LANG, false);
		layoutMenu.addView(MenuFirst);
		layoutMenu.addView(MenuSecond);
		layoutContent = linearLayout(1, this);
		sv = scrollView(this);
		sv.addView(layoutContent);
		btnLangGuo = contentButton(R.string.songquery_lang_guo);
		btnLangTai = contentButton(R.string.songquery_lang_tai);
		btnLangYuei = contentButton(R.string.songquery_lang_yuei);
		btnLangJpn = contentButton(R.string.songquery_lang_jpn);
		btnLangEng = contentButton(R.string.songquery_lang_eng);
		btnLangKer = contentButton(R.string.songquery_lang_ker);
		btnLangOther = contentButton(R.string.songquery_lang_other);
		btnLangKid = contentButton(R.string.songquery_lang_kid);

		layoutContent.addView(btnLangGuo);
		layoutContent.addView(btnLangTai);
		layoutContent.addView(btnLangYuei);
		layoutContent.addView(btnLangJpn);
		layoutContent.addView(btnLangEng);
		layoutContent.addView(btnLangKer);
		layoutContent.addView(btnLangOther);
		layoutContent.addView(btnLangKid);
		layoutMain.addView(sv);
		backAction = MenuType.MAIN;
		setContentView(layoutMain);

		btnLangGuo.setOnClickListener(setLangOCL(MenuType.LANG_GUO));
		btnLangTai.setOnClickListener(setLangOCL(MenuType.LANG_TAI));
		btnLangYuei.setOnClickListener(setLangOCL(MenuType.LANG_YUEI));
		btnLangJpn.setOnClickListener(setLangOCL(MenuType.LANG_JPN));
		btnLangEng.setOnClickListener(setLangOCL(MenuType.LANG_ENG));
		btnLangKer.setOnClickListener(setLangOCL(MenuType.LANG_KER));
		btnLangOther.setOnClickListener(setLangOCL(MenuType.LANG_OTHER));
		btnLangKid.setOnClickListener(setLangOCL(MenuType.LANG_KID));

	}

	private OnClickListener setLangOCL(final MenuType mt) {
		OnClickListener ocl = new View.OnClickListener() {
			public void onClick(View v) {
				setWordMenu(mt);
			}
		};
		return ocl;
	}

	private void setWordMenu(MenuType mt) {
		layoutMain = linearLayout(1, this);
		layoutMenu = linearLayout(0, this);
		layoutMenu.setPadding(10, 5, 0, 10);
		layoutMain.addView(layoutMenu);
		MenuFirst = menuText(MenuType.MAIN, true);
		MenuSecond = menuText(MenuType.LANG, true);
		MenuThird = menuText(mt, false);
		layoutMenu.addView(MenuFirst);
		layoutMenu.addView(MenuSecond);
		layoutMenu.addView(MenuThird);
		layoutContent = linearLayout(1, this);
		sv = scrollView(this);
		sv.addView(layoutContent);
		/*
		 * sv = new ScrollView(this); sv.setPadding(0, 0, 0, 10);
		 * sv.setFadingEdgeLength(40); sv.setVerticalFadingEdgeEnabled(true);
		 * sv.addView(layoutContent);
		 */
		layoutMain.addView(sv);
		btnWord1 = contentButton(R.string.songquery_word_1);
		btnWord2 = contentButton(R.string.songquery_word_2);
		btnWord3 = contentButton(R.string.songquery_word_3);
		btnWord4 = contentButton(R.string.songquery_word_4);
		btnWord5 = contentButton(R.string.songquery_word_5);
		btnWord6 = contentButton(R.string.songquery_word_6);
		btnWord7 = contentButton(R.string.songquery_word_7);
		btnWord8 = contentButton(R.string.songquery_word_8);
		btnWord9 = contentButton(R.string.songquery_word_9);
		btnWord0 = contentButton(R.string.songquery_word_0);
		layoutContent.addView(btnWord1);
		layoutContent.addView(btnWord2);
		layoutContent.addView(btnWord3);
		layoutContent.addView(btnWord4);
		layoutContent.addView(btnWord5);
		layoutContent.addView(btnWord6);
		layoutContent.addView(btnWord7);
		layoutContent.addView(btnWord8);
		layoutContent.addView(btnWord9);
		layoutContent.addView(btnWord0);
		btnWord1.setOnClickListener(setWordOCL(mt, 1));
		btnWord2.setOnClickListener(setWordOCL(mt, 2));
		btnWord3.setOnClickListener(setWordOCL(mt, 3));
		btnWord4.setOnClickListener(setWordOCL(mt, 4));
		btnWord5.setOnClickListener(setWordOCL(mt, 5));
		btnWord6.setOnClickListener(setWordOCL(mt, 6));
		btnWord7.setOnClickListener(setWordOCL(mt, 7));
		btnWord8.setOnClickListener(setWordOCL(mt, 8));
		btnWord9.setOnClickListener(setWordOCL(mt, 9));
		btnWord0.setOnClickListener(setWordOCL(mt, 0));
		backAction = MenuType.LANG;
		setContentView(layoutMain);
	}

	private OnClickListener setWordOCL(final MenuType mt, final int i) {
		OnClickListener ocl = new View.OnClickListener() {
			public void onClick(View v) {
				String code = null, word = null;
				switch (mt) {
				case LANG_GUO:
					code = Util.LangList.GUO.getValue();
					break;
				case LANG_TAI:
					code = Util.LangList.TAI.getValue();
					break;
				case LANG_YUEI:
					code = Util.LangList.YUEI.getValue();
					break;
				case LANG_JPN:
					code = Util.LangList.JPN.getValue();
					break;
				case LANG_ENG:
					code = Util.LangList.ENG.getValue();
					break;
				case LANG_KER:
					code = Util.LangList.KER.getValue();
					break;
				case LANG_OTHER:
					code = Util.LangList.OTHER.getValue();
					break;
				case LANG_KID:
					code = Util.LangList.KID.getValue();
					break;
				default:
				}
				switch (i) {
				case 1:
					word = (String) getText(R.string.songquery_word_1);
					break;
				case 2:
					word = (String) getText(R.string.songquery_word_2);
					break;
				case 3:
					word = (String) getText(R.string.songquery_word_3);
					break;
				case 4:
					word = (String) getText(R.string.songquery_word_4);
					break;
				case 5:
					word = (String) getText(R.string.songquery_word_5);
					break;
				case 6:
					word = (String) getText(R.string.songquery_word_6);
					break;
				case 7:
					word = (String) getText(R.string.songquery_word_7);
					break;
				case 8:
					word = (String) getText(R.string.songquery_word_8);
					break;
				case 9:
					word = (String) getText(R.string.songquery_word_9);
					break;
				case 0:
					word = (String) getText(R.string.songquery_word_0);
					break;
				default:
				}
				String value = "Song_WordCount=" + i
						+ "&sort=Song_SongName&lang=" + code;
				if (i == 0) {
					value = "Song_WordCount%3E9&sort=Song_SongName&lang="
							+ code;
				}

				getSongList(MenuType.LANG, mt, word, Util.QuerySong(value));
			}
		};
		return ocl;
	}

	private void setMultiMenu() {
		layoutMain = linearLayout(1, this);
		layoutMenu = linearLayout(0, this);
		layoutMenu.setPadding(10, 5, 0, 10);
		layoutMain.addView(layoutMenu);
		MenuFirst = menuText(MenuType.MAIN, true);
		MenuSecond = menuText(MenuType.MULTI, false);
		layoutMenu.addView(MenuFirst);
		layoutMenu.addView(MenuSecond);
		btnLangGuo = contentButton(R.string.songquery_multi_guo);
		btnLangTai = contentButton(R.string.songquery_multi_tai);
		btnLangYuei = contentButton(R.string.songquery_multi_yuei);
		btnLangJpn = contentButton(R.string.songquery_multi_jpn);
		btnLangEng = contentButton(R.string.songquery_multi_eng);
		btnLangKer = contentButton(R.string.songquery_multi_ker);
		layoutMain.addView(btnLangGuo);
		layoutMain.addView(btnLangTai);
		layoutMain.addView(btnLangYuei);
		layoutMain.addView(btnLangJpn);
		layoutMain.addView(btnLangEng);
		layoutMain.addView(btnLangKer);
		backAction = MenuType.MAIN;
		setContentView(layoutMain);

		btnLangGuo.setOnClickListener(setMultiOCL(MenuType.RANK_GUO));
		btnLangTai.setOnClickListener(setMultiOCL(MenuType.RANK_TAI));
		btnLangYuei.setOnClickListener(setMultiOCL(MenuType.RANK_YUEI));
		btnLangJpn.setOnClickListener(setMultiOCL(MenuType.RANK_JPN));
		btnLangEng.setOnClickListener(setMultiOCL(MenuType.RANK_ENG));
		btnLangKer.setOnClickListener(setMultiOCL(MenuType.RANK_KER));
	}

	private OnClickListener setMultiOCL(final MenuType mt) {
		OnClickListener ocl = new View.OnClickListener() {
			public void onClick(View v) {
				String lang = null;
				switch (mt) {
				case RANK_GUO:
					lang = LangList.GUO.getValue();
					break;
				case RANK_TAI:
					lang = LangList.TAI.getValue();
					break;
				case RANK_YUEI:
					lang = LangList.YUEI.getValue();
					break;
				case RANK_JPN:
					lang = LangList.JPN.getValue();
					break;
				case RANK_ENG:
					lang = LangList.ENG.getValue();
					break;
				case RANK_KER:
					lang = LangList.KER.getValue();
					break;
				case RANK_OTHER:
					lang = LangList.OTHER.getValue();
					break;
				case RANK_KID:
					lang = LangList.KID.getValue();
					break;
				default:
				}
				String value = "Song_SingerType=3&sort=Song_WordCount,Song_SongName&lang="
						+ lang + "&sort=Song_PlayCount%20DESC";
				getSongList(MenuType.MULTI, mt, null, Util.QuerySong(value));
			}
		};
		return ocl;
	}

	private void setRankMenu() {
		layoutMain = linearLayout(1, this);
		layoutMenu = linearLayout(0, this);
		layoutMenu.setPadding(10, 5, 0, 10);
		layoutMain.addView(layoutMenu);
		MenuFirst = menuText(MenuType.MAIN, true);
		MenuSecond = menuText(MenuType.RANK, false);
		layoutMenu.addView(MenuFirst);
		layoutMenu.addView(MenuSecond);
		btnLangGuo = contentButton(R.string.songquery_rank_guo);
		btnLangTai = contentButton(R.string.songquery_rank_tai);
		btnLangYuei = contentButton(R.string.songquery_rank_yuei);
		btnLangJpn = contentButton(R.string.songquery_rank_jpn);
		btnLangEng = contentButton(R.string.songquery_rank_eng);
		btnLangKer = contentButton(R.string.songquery_rank_ker);
		btnLangOther = contentButton(R.string.songquery_rank_other);
		btnLangKid = contentButton(R.string.songquery_rank_kid);
		layoutMain.addView(btnLangGuo);
		layoutMain.addView(btnLangTai);
		layoutMain.addView(btnLangYuei);
		layoutMain.addView(btnLangJpn);
		layoutMain.addView(btnLangEng);
		layoutMain.addView(btnLangKer);
		layoutMain.addView(btnLangOther);
		layoutMain.addView(btnLangKid);
		backAction = MenuType.MAIN;
		setContentView(layoutMain);

		btnLangGuo.setOnClickListener(setRankOCL(MenuType.RANK_GUO));
		btnLangTai.setOnClickListener(setRankOCL(MenuType.RANK_TAI));
		btnLangYuei.setOnClickListener(setRankOCL(MenuType.RANK_YUEI));
		btnLangJpn.setOnClickListener(setRankOCL(MenuType.RANK_JPN));
		btnLangEng.setOnClickListener(setRankOCL(MenuType.RANK_ENG));
		btnLangKer.setOnClickListener(setRankOCL(MenuType.RANK_KER));
		btnLangOther.setOnClickListener(setRankOCL(MenuType.RANK_OTHER));
		btnLangKid.setOnClickListener(setRankOCL(MenuType.RANK_KID));
	}

	private OnClickListener setRankOCL(final MenuType mt) {
		OnClickListener ocl = new View.OnClickListener() {
			public void onClick(View v) {
				String rank = null;
				switch (mt) {
				case RANK_GUO:
					rank = LangList.GUO.getValue();
					break;
				case RANK_TAI:
					rank = LangList.TAI.getValue();
					break;
				case RANK_YUEI:
					rank = LangList.YUEI.getValue();
					break;
				case RANK_JPN:
					rank = LangList.JPN.getValue();
					break;
				case RANK_ENG:
					rank = LangList.ENG.getValue();
					break;
				case RANK_KER:
					rank = LangList.KER.getValue();
					break;
				case RANK_OTHER:
					rank = LangList.OTHER.getValue();
					break;
				case RANK_KID:
					rank = LangList.KID.getValue();
					break;
				default:
				}
				String value = "Song_PlayCount%3E" + Util.prefRank + "&lang="
						+ rank + "&sort=Song_PlayCount%20DESC";
				getSongList(MenuType.RANK, mt, null,
						Util.QuerySong(value, Util.prefQueryRankRows));
			}
		};
		return ocl;
	}

	private void getFavaoriteList() {
		layoutMain = linearLayout(1, this);
		layoutMenu = linearLayout(0, this);
		layoutMenu.setPadding(10, 5, 0, 10);
		layoutMain.addView(layoutMenu);
		MenuFirst = menuText(MenuType.MAIN, true);
		MenuSecond = menuText(MenuType.WHOSFAVORITE, false);
		layoutMenu.addView(MenuFirst);
		layoutMenu.addView(MenuSecond);

		lv = listView();

		// get list
		ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

		try {
			JSONArray jsonArray = new JSONArray(Util.FavoriteUser());
			for (int i = 0; i < jsonArray.length(); i++) {
				HashMap<String, String> map = new HashMap<String, String>();
				JSONObject e = jsonArray.getJSONObject(i);
				map.put("id", e.getString("User_Id"));
				map.put("user", e.getString("User_Name"));
				mylist.add(map);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		// readJSON

		ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.list1,
				new String[] { "id", "user" }, new int[] { R.id.text1,
						R.id.text2 });
		lv.setAdapter(adapter);
		registerForContextMenu(lv);
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> a, View v, int position,
					long id) {
				TextView tvId = (TextView) v.findViewById(R.id.text1);
				getSongList(MenuType.WHOSFAVORITE, MenuType.FAVORITE, null,
						Util.FavoriteSong(tvId.getText().toString()));
			}
		});

		layoutMain.addView(lv);

		backAction = MenuType.MAIN;
		setContentView(layoutMain);
	}

	private void getSongList(MenuType second, MenuType third, String fourth,
			String string) {
		WindowManager mWinMgr = (WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE);
		int displayWidth = mWinMgr.getDefaultDisplay().getWidth();
		layoutMain = linearLayout(1, this);
		layoutMenu = linearLayout(0, this);
		layoutMenu.setPadding(10, 5, 0, 10);
		layoutMain.addView(layoutMenu);
		MenuFirst = menuText(MenuType.MAIN, true);
		MenuSecond = menuText(second, (third == null) ? false : true);
		if (displayWidth > 240) {
			layoutMenu.addView(MenuFirst);
		}
		layoutMenu.addView(MenuSecond);

		if (third != null) {
			MenuThird = menuText(third, (fourth == null) ? false : true);
			layoutMenu.addView(MenuThird);
		}
		if (fourth != null) {
			MenuFourth = menuText(fourth);
			layoutMenu.addView(MenuFourth);
		}
		lv = listView();

		// get list
		final Boolean isFavorite;
		isFavorite = (second == MenuType.FAVORITE) ? true : false;

		ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

		try {
			JSONArray jsonArray = new JSONArray(string);
			for (int i = 0; i < jsonArray.length(); i++) {
				HashMap<String, String> map = new HashMap<String, String>();
				JSONObject e = jsonArray.getJSONObject(i);
				map.put("id", e.getString("Song_Id"));
				map.put("stroke", e.getString("Song_SongStroke") + " 劃");
				map.put("singer", e.getString("Song_Singer"));
				map.put("title", e.getString("Song_SongName"));
				map.put("type", e.getString("Song_Lang"));
				mylist.add(map);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		// readJSON

		ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.list2,
				new String[] { "id", "stroke", "singer", "title", "type" },
				new int[] { R.id.text1, R.id.text2, R.id.text3, R.id.text4,
						R.id.text5 });
		lv.setAdapter(adapter);
		registerForContextMenu(lv);
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> a, View v, int position,
					long id) {
				TextView tvId = (TextView) v.findViewById(R.id.text1);
				TextView tvSinger = (TextView) v.findViewById(R.id.text3);
				TextView tvTitle = (TextView) v.findViewById(R.id.text4);
				String singer = tvSinger.getText().toString();
				String title = tvTitle.getText().toString();
				orderDialog(Integer.valueOf(tvId.getText().toString()),
						singer + " - " + title, isFavorite).show();
			}
		});

		layoutMain.addView(lv);

		if ((second == MenuType.RANK) || (second == MenuType.MULTI)) {
			backAction = second;
		} else if (second == MenuType.WHOSFAVORITE) {
			backAction = MenuType.MAIN;
		} else if (second == MenuType.SONG_NAME) {
			backAction = MenuType.MAIN;
		} else if (second == MenuType.NEW_SONG) {
			backAction = MenuType.MAIN;
		} else if (third != null) {
			backAction = third;
		}
		if (third == MenuType.FAVORITE) {
			backAction = third;
		}
		setContentView(layoutMain);
	}

	private AlertDialog orderDialog(final int i, final String song,
			Boolean isFavorite) {
		// 產生一個Builder物件
		Builder builder = new AlertDialog.Builder(SongQuery.this);
		// 設定Dialog的標題
		builder.setTitle(R.string.order_dialog_title);
		// 設定Dialog的內容
		builder.setMessage(song);
		// 設定Negative按鈕資料

		/*
		 * if (isFavorite) {
		 * builder.setNegativeButton(R.string.order_del_favorite, new
		 * DialogInterface.OnClickListener() { public void
		 * onClick(DialogInterface dialog, int which) { tm = (TelephonyManager)
		 * getSystemService(Context.TELEPHONY_SERVICE); String imei =
		 * tm.getDeviceId(); sendCode(Command.FAVORITEDEL.getValue() + ":" +
		 * imei + ":" + String.valueOf(i)); myVibrator.vibrate(100);
		 * getSongList(MenuType.FAVORITE, null, null,
		 * Command.FAVORITELIST.getValue() + ":" + imei + ":"); } }); } else {
		 * builder.setNegativeButton(R.string.order_add_favorite, new
		 * DialogInterface.OnClickListener() { public void
		 * onClick(DialogInterface dialog, int which) { tm = (TelephonyManager)
		 * getSystemService(Context.TELEPHONY_SERVICE); String imei =
		 * tm.getDeviceId(); sendCode(Command.FAVORITEADD.getValue() + ":" +
		 * imei + ":" + String.valueOf(i)); myVibrator.vibrate(100); } }); }
		 */

		builder.setNeutralButton(R.string.string_insert,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String s = Util.DoAction(DoAction.INSERT,
								String.valueOf(i));
						if (s.length() < 5) {
							Toast.makeText(
									SongQuery.this,
									song
											+ " "
											+ getText(R.string.toast_insert_success),
									Toast.LENGTH_SHORT).show();
							myVibrator.vibrate(100);
						} else {
							Log.d("insert", s);
							Toast.makeText(SongQuery.this,
									R.string.toast_order_fail,
									Toast.LENGTH_SHORT).show();
						}
					}
				});

		// 設定Positive按鈕資料
		builder.setPositiveButton(R.string.string_order,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						try {
							JSONArray jsona = new JSONArray(Util
									.OrderSong(String.valueOf(i)));
							JSONObject json = new JSONObject(jsona.getString(0));
							String s = json.getString("Song_SongName");
							if (s.length() != 0) {
								Toast.makeText(
										SongQuery.this,
										song
												+ " "
												+ getText(R.string.toast_order_success),
										Toast.LENGTH_SHORT).show();
								myVibrator.vibrate(100);
							}
						} catch (Exception e) {
							e.printStackTrace();
							Toast.makeText(SongQuery.this,
									R.string.toast_order_fail,
									Toast.LENGTH_SHORT).show();
						}
					}
				});

		// 利用Builder物件建立AlertDialog
		return builder.create();
	}

	private AlertDialog querySongNameDialog() {
		// 產生一個Builder物件
		Builder builder = new AlertDialog.Builder(SongQuery.this);
		// 設定Dialog的標題
		builder.setTitle(R.string.songquery_song_name);
		// 設定Dialog的內容
		final EditText et = new EditText(this);
		et.setMaxLines(1);
		builder.setView(et);

		builder.setNegativeButton(android.R.string.cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
				});

		builder.setPositiveButton(android.R.string.ok,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (!(et.getText().length() == 0)) {
							String t = et.getText().toString();
							t = t.replace(" ", "%20");
							t = t.replace("'", "%27");
							String value = "Song_SongName+like+%27%2A" + t
									+ "%2A%27";
							getSongList(MenuType.SONG_NAME, null, null,
									Util.QuerySong(value));
						}

					}
				});

		// 利用Builder物件建立AlertDialog
		return builder.create();
	}

	// TODO layout layer content
	public static LinearLayout linearLayout(int orient, Context context) {
		LinearLayout l = new LinearLayout(context);
		l.setLayoutParams(new Gallery.LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT));
		l.setOrientation(orient);
		return l;
	}

	// TODO make Button
	private Button contentButton(int i) {
		Button b = new Button(this);
		b.setText(i);
		b.setTextSize(2, 30);
		return b;
	}

	public static ScrollView scrollView(Context context) {
		ScrollView s = new ScrollView(context);
		s.setPadding(0, 0, 0, 0);
		s.setFadingEdgeLength(40);
		s.setVerticalFadingEdgeEnabled(true);
		return s;
	}

	private ListView listView() {
		ListView lv = new ListView(this);
		lv.setFastScrollEnabled(true);
		lv.setVerticalFadingEdgeEnabled(true);
		lv.setFadingEdgeLength(20);
		return lv;
	}

	// TODO enum
	private static enum MenuType {
		MAIN(R.string.songquery_main), SINGER(R.string.songquery_singer), SINGER_MALE(
				R.string.songquery_singer_male), SINGER_FEMALE(
				R.string.songquery_singer_female), SINGER_GROUP(
				R.string.songquery_singer_group), SINGER_QUERY(
				R.string.songquery_singer_query), LANG(R.string.songquery_lang), LANG_GUO(
				R.string.songquery_lang_guo), LANG_TAI(
				R.string.songquery_lang_tai), LANG_YUEI(
				R.string.songquery_lang_yuei), LANG_JPN(
				R.string.songquery_lang_jpn), LANG_ENG(
				R.string.songquery_lang_eng), LANG_KER(
				R.string.songquery_lang_ker), LANG_OTHER(
				R.string.songquery_lang_other), LANG_KID(
				R.string.songquery_lang_kid), MULTI(R.string.songquery_multi), MULTI_GUO(
				R.string.songquery_multi_guo), MULTI_TAI(
				R.string.songquery_multi_tai), MULTI_YUEI(
				R.string.songquery_multi_yuei), MULTI_JPN(
				R.string.songquery_multi_jpn), MULTI_ENG(
				R.string.songquery_multi_eng), MULTI_KER(
				R.string.songquery_multi_ker), WHOSFAVORITE(
				R.string.songquery_whos_favorite), FAVORITE(
				R.string.songquery_favorite), RANK(R.string.songquery_rank), RANK_GUO(
				R.string.songquery_rank_guo), RANK_TAI(
				R.string.songquery_rank_tai), RANK_YUEI(
				R.string.songquery_rank_yuei), RANK_JPN(
				R.string.songquery_rank_jpn), RANK_ENG(
				R.string.songquery_rank_eng), RANK_KER(
				R.string.songquery_rank_ker), RANK_OTHER(
				R.string.songquery_rank_other), RANK_KID(
				R.string.songquery_rank_kid), NEW_SONG(
				R.string.songquery_new_song), SONG_NAME(
				R.string.songquery_song_name), QUIT(R.string.quit);
		private int menu;

		MenuType(int menu) {
			this.menu = menu;
		}

		public int getValue() {
			return menu;
		}
	}

	// TODO Menu Text
	private TextView menuText(final MenuType text, boolean link) {
		TextView t = new TextView(this);
		t.setText(text.getValue());
		t.setTextSize(2, 18);
		t.setPadding(0, 0, 0, 0);
		if (link) {
			t.append(" > ");
			t.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					switch (text) {
					case MAIN:
						setMainMenu();
						break;
					case SINGER:
						setSingerMenu();
						break;
					case SINGER_MALE:
						getSingerList(text);
						break;
					case SINGER_FEMALE:
						getSingerList(text);
						break;
					case SINGER_GROUP:
						getSingerList(text);
						break;
					/*
					 * case SINGER_QUERY: setSingerMenu(); break;
					 */
					case LANG:
						setLangMenu();
						break;
					case LANG_GUO:
						setWordMenu(text);
						break;
					case LANG_TAI:
						setWordMenu(text);
						break;
					case LANG_YUEI:
						setWordMenu(text);
						break;
					case LANG_JPN:
						setWordMenu(text);
						break;
					case LANG_ENG:
						setWordMenu(text);
						break;
					case LANG_KER:
						setWordMenu(text);
						break;
					case LANG_OTHER:
						setWordMenu(text);
						break;
					case LANG_KID:
						setWordMenu(text);
						break;
					/*
					 * case WHOSFAVORITE: getFavaoriteList(); break;
					 */
					case MULTI:
						setMultiMenu();
					case RANK:
						setRankMenu();
						break;
					default:
					}
				}
			});
		}

		return t;
	}

	private TextView menuText(String s) {
		TextView t = new TextView(this);
		t.setText(s);
		t.setTextSize(2, 18);
		t.setPadding(0, 0, 0, 0);
		return t;
	}

	// listen "back" action
	private long exitTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			switch (backAction) {
			case QUIT:
				if ((System.currentTimeMillis() - exitTime) > 2000) {
					Toast.makeText(getApplicationContext(), R.string.quit,
							Toast.LENGTH_SHORT).show();
					exitTime = System.currentTimeMillis();
				} else {
					finish();
					System.exit(0);
				}
				break;
			case MAIN:
				setMainMenu();
				break;
			case SINGER:
				setSingerMenu();
				break;
			case LANG:
				setLangMenu();
				break;
			case MULTI:
				setMultiMenu();
				break;
			case FAVORITE:
				getFavaoriteList();
				break;
			case RANK:
				setRankMenu();
				break;
			case SINGER_MALE:
				getSingerList(backAction);
				break;
			case SINGER_FEMALE:
				getSingerList(backAction);
				break;
			case SINGER_GROUP:
				getSingerList(backAction);
				break;
			case SINGER_QUERY:
				setSingerMenu();
				break;
			case LANG_GUO:
				setWordMenu(backAction);
				break;
			case LANG_TAI:
				setWordMenu(backAction);
				break;
			case LANG_YUEI:
				setWordMenu(backAction);
				break;
			case LANG_JPN:
				setWordMenu(backAction);
				break;
			case LANG_ENG:
				setWordMenu(backAction);
				break;
			case LANG_KER:
				setWordMenu(backAction);
				break;
			case LANG_OTHER:
				setWordMenu(backAction);
				break;
			case LANG_KID:
				setWordMenu(backAction);
				break;

			default:
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
